package
{
	import flash.utils.Dictionary;
	
	import org.flixel.*;
	
	public class ChallengeFriendsComponent extends FlxGroup
	{
		private static const CHALLENGED:int = 1;
		private static const NOT_CHALLENGED:int = 0;
		
		public static const WIDTH:int = 400;
		public static const HEIGHT:int = 600;
		private static const ROWS:int = 10;
		
		protected var friendSortable:Array;
		protected var friendIDs:Array;
		protected var friendStatuses:Array;
		
		protected var prevButton:FlxSprite;
		protected var nextButton:FlxSprite;
		protected var closeButton:FlxSprite;
		protected var sendButton:FlxSprite;
		protected var currentPage:int;
		
		protected var nameToIndex:Dictionary;
		
		protected var currentNames:Vector.<ChallengeListing>;
		protected var done:Boolean;
		
		protected var startX:int;
		protected var startY:int;
		protected var mapID:int;
		
		public function ChallengeFriendsComponent(mapID:int, x:int, y:int)
		{
			this.mapID = mapID;
			startX = x;
			startY = y;
			
			currentPage = 1;
			currentNames = new Vector.<ChallengeListing>();
			
			sortFriends();
			
			initStuff();
			createPage();
			
			done = false;
		}
		
		private function initStuff():void {
			add(new FlxSprite(0, 0, Res.Backdrop));
			
			var bg:FlxSprite = new FlxSprite(startX, startY, Res.Panel);
			add(bg);
			
			sendButton = new FlxSprite(0, startY + 20, Res.sendButton);
			sendButton.x = startX + (WIDTH/2) - sendButton.width - 5;
			add(sendButton);
			
			closeButton = new FlxSprite(0, startY + 20, Res.cancelButton);
			closeButton.x = startX + (WIDTH/2) + 5;
			add(closeButton);
			
			prevButton = new FlxSprite(startX + 20, startY + 20, Res.prevButton);
			
			nextButton = new FlxSprite(0, startY + 20, Res.nextButton);
			nextButton.x = startX + WIDTH - nextButton.width - 20;
			
			var title:FlxText = new FlxText(bg.x, nextButton.y + nextButton.height + 15, bg.width, "Select friends to challenge:", false);
			title.setFormat("Georgia", 24, 0x000000, "center", 0, true);
			add(title);
		}
		
		private function sortFriends():void {
			var friends:Array = Elemental.fbInfo.friends;
			friendSortable = new Array();
			friendIDs = new Array();
			friendStatuses = new Array();
			nameToIndex = new Dictionary();
			
			for (var i:int = 0; i < friends.length; i++) {
				friendSortable.push(friends[i]["name"]);
				friendIDs.push(friends[i]["id"]);
				friendStatuses.push(CHALLENGED);
				nameToIndex[friends[i]["name"]] = i;
			}
			friendSortable.sort(compareFriends);
		}
		
		private function compareFriends(one:String, two:String):int {
			if (one.toLowerCase() == two.toLowerCase()) {
				return 0;
			} else if (one.toLowerCase() < two.toLowerCase()) {
				return -1;
			} else {
				return 1;
			}
			return 0;
		}
		
		/**
		 * Creates a single page for the currentPage
		 */
		private function createPage():void {
			var startIndex:int = (currentPage-1) * ROWS;
			for (var i:int = 0; i < ROWS; i++) {
				if (startIndex + i >= friendSortable.length) {
					break;
				}
				
				var xPos:int = startX + (WIDTH - ChallengeListing.WIDTH)/2;
				var yPos:int = startY + 110 + (45 * i);
				
				var listing:ChallengeListing = new ChallengeListing(friendSortable[startIndex + i], startIndex + i, friendStatuses[startIndex + i], xPos, yPos);
				currentNames.push(listing);
				add(listing);
			}
			
			updatePageArrows();
		}
		
		/**
		 * Adds the page arrows as necessary
		 */
		private function updatePageArrows():void {
			var totalPages:int = Math.ceil(friendSortable.length / ROWS);
			if (currentPage > 1) add(prevButton);
			if (currentPage < totalPages) add(nextButton);
		}
		
		/**
		 * Cleans out existing page and populates it with stuff for the requested page
		 */
		private function requestNewPage(requestedPage:int):void {
			var totalPages:int = Math.ceil(friendSortable.length / ROWS);
			if (requestedPage < 1 || requestedPage > totalPages) {
				return;
			}
			
			currentPage = requestedPage;
			remove(prevButton);
			remove(nextButton);
			
			updateChallenges();
			createPage();
		}
		
		/**
		 * Before we create the new page,
		 * look at the current names and retrieve the challenge status for each.
		 * Save them to somewhere.
		 * Then clear out the names vector.
		 */
		private function updateChallenges():void {
			for (var i:int = 0; i < currentNames.length; i++) {
				var cl:ChallengeListing = currentNames[i];
				var status:int = cl.getStatus();
				var index:int = nameToIndex[cl.getName()];// cl.getIndex();

				friendStatuses[index] = status;
				remove(cl);
			}
			
			currentNames = new Vector.<ChallengeListing>();
		}
		
		public override function update():void  {
			super.update();
			
			if (FlxG.mouse.justPressed() && prevButton.overlapsPoint(FlxG.mouse.screenX, FlxG.mouse.screenY)) {
				requestNewPage(currentPage - 1);
			}
			
			if (FlxG.mouse.justPressed() && nextButton.overlapsPoint(FlxG.mouse.screenX, FlxG.mouse.screenY)) {
				requestNewPage(currentPage + 1);
			}
			
			if (FlxG.mouse.justPressed() && closeButton.overlapsPoint(FlxG.mouse.x, FlxG.mouse.y)) {
				updateChallenges();
				done = true;
			}
			
			if (FlxG.mouse.justPressed() && sendButton.overlapsPoint(FlxG.mouse.x, FlxG.mouse.y)) {
				updateChallenges();
				// do the request
				// show successful submission
				var challengedIds:String = "";
				for (var i:int = 0; i < friendStatuses.length; i++) {
					if (friendStatuses[i] == CHALLENGED) {
						challengedIds += friendIDs[i] + ":";
					}
				}
				if (challengedIds.length > 0) {
					challengedIds = challengedIds.substr(0, challengedIds.length - 1);
					trace(challengedIds);
					Client.issueChallenge(challengedIds, Elemental.fbInfo.userID, new String(mapID));
				}
				Elemental.Log.logChallenge(challengedIds, Elemental.fbInfo.userID,new String(mapID));
				done = true;
			}
		}
			
		public function finishedChallenging():Boolean {
			return done;
		}
	}
}